(* Copyright (C) 2017 Hongbo Zhang, Authors of ReScript
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * In addition to the permissions granted to you by the LGPL, you may combine
 * or link a "work that uses the Library" with a publicly distributed version
 * of this file to produce a combined library or application, then distribute
 * that combined work under the terms of your choosing, with no requirement
 * to comply with the obligations normally placed on you by section 4 of the
 * LGPL version 3 (or the corresponding section of a later version of the LGPL
 * should you choose to use a later version).
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)

open Import
module P = Js_pp
module L = Js_dump_lit

let empty_explanation =
  "/* This output is empty. Its source's type definitions, externals and/or \
   unused code got optimized away. */\n"

let program_is_empty (x : J.program) =
  match x with
  | { block = []; exports = []; export_set = _ } -> true
  | _ -> false

let deps_program_is_empty (x : J.deps_program) =
  match x with
  | { modules = []; program; side_effect = None; _ } -> program_is_empty program
  | _ -> false

let rec extract_block_comments acc (x : J.block) =
  match x with
  | {
      statement_desc =
        Exp
          {
            expression_desc =
              Raw_js_code { code; code_info = Stmt Js_stmt_comment; _ };
            _;
          };
      _;
    }
    :: rest ->
      extract_block_comments (code :: acc) rest
  | _ -> (acc, x)

let extract_file_comments (x : J.deps_program) =
  let comments, new_block = extract_block_comments [] x.program.block in
  (comments, { x with program = { x.program with block = new_block } })

let program ~output_dir ~package_info ~output_info f cxt (x : J.program) =
  P.at_least_two_lines f;
  let cxt =
    Js_dump.statements ~top:true ~scope:cxt ~output_dir ~package_info
      ~output_info f x.block
  in
  Js_dump_import_export.module_exports cxt f x.exports

let dump_program ~output_dir ~package_info ~output_info (x : J.program) oc =
  ignore
    (program ~output_dir ~package_info ~output_info (P.from_fd oc)
       Js_pp.Scope.empty x)

let modules ~output_dir ~package_info ~output_info (x : J.deps_program) =
  List.filter_map x.modules ~f:(fun (x : Lam_module_ident.t) ->
      match x.dynamic_import with
      | true -> None
      | false ->
          Some
            {
              Js_dump_import_export.id = x.id;
              path =
                Js_name_of_module_id.string_of_module_id ~package_info
                  ~output_info ~output_dir x;
              default =
                (match x.kind with
                | External { default; _ } -> default
                | _ -> false);
            })

let node_program ~output_dir ~package_info ~output_info f (x : J.deps_program) =
  P.string f L.strict_directive;
  P.newline f;
  let cxt =
    Js_dump_import_export.requires Js_pp.Scope.empty f
      (modules ~package_info ~output_info ~output_dir x)
  in
  program ~output_dir ~package_info ~output_info f cxt x.program

let es6_program ~package_info ~output_info ~output_dir f (x : J.deps_program) =
  let cxt =
    Js_dump_import_export.imports Js_pp.Scope.empty f
      (modules ~package_info ~output_info ~output_dir x)
  in
  let () = P.at_least_two_lines f in
  let cxt =
    Js_dump.statements ~top:true ~output_dir ~output_info ~package_info
      ~scope:cxt f x.program.block
  in
  Js_dump_import_export.es6_export cxt f x.program.exports

let pp_deps_program =
  let header = "// Generated by Melange" in
  let no_side_effect = "/* No side effect */" in

  fun ~package_info
    ~(output_info : Js_packages_info.output_info)
    ~(output_prefix : string)
    (f : Js_pp.t)
    (program : J.deps_program)
  ->
    Option.iter
      ~f:(fun preamble ->
        P.string f preamble;
        P.newline f)
      program.preamble;
    if not !Js_config.no_version_header then (
      P.string f header;
      P.newline f);
    if deps_program_is_empty program then P.string f empty_explanation
      (* This is empty module, it won't be referred anywhere *)
    else
      let comments, program = extract_file_comments program in
      List.rev_iter comments ~f:(fun comment ->
          P.string f comment;
          P.newline f);
      let output_dir = Filename.dirname output_prefix in
      ignore
        (match output_info.module_system with
        | ESM | ESM_global ->
            es6_program ~package_info ~output_dir ~output_info f program
        | CommonJS ->
            node_program ~package_info ~output_info ~output_dir f program);
      P.newline f;
      P.string f
        (match program.side_effect with
        | None -> no_side_effect
        | Some v -> Printf.sprintf "/* %s Not a pure module */" v);
      P.newline f;
      P.flush f ()

let dump_deps_program ~package_info ~output_info ~output_prefix x
    (oc : Unix.file_descr) =
  pp_deps_program ~package_info ~output_info ~output_prefix (P.from_fd oc) x
